﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using SimpleNotify.Service.Contracts;
using System.Configuration.Install;
using System.ServiceModel.Description;
using System.IO;

namespace SimpleNotify.WindowsService
{
    public partial class WindowsService : ServiceBase
    {
        private ServiceHost _serviceHost = null;

        public WindowsService()
        {
            InitializeComponent();
            ServiceName = "Simple Notify Service";
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                if (_serviceHost != null)
                {
                    _serviceHost.Close();
                }

                _serviceHost = SetupWcfService();
                _serviceHost.Open();
                File.AppendAllText("SimpleNotify.Service.log", DateTime.Now.ToString() + " | Host Info | Service successfully started");
            }
            catch (Exception ex)
            {
                File.AppendAllText("SimpleNotify.Service.log", DateTime.Now.ToString() + " | Host Error | Error starting the service: " + ex.ToString());
            }
        }

        protected override void OnStop()
        {
            try
            {
                if (_serviceHost != null)
                {
                    _serviceHost.Close();
                    _serviceHost = null;
                }

                File.AppendAllText("SimpleNotify.Service.log", DateTime.Now.ToString() + " | Host Info | Service successfully stopped");
            }
            catch (Exception ex)
            {
                File.AppendAllText("SimpleNotify.Service.log", DateTime.Now.ToString() + " | Host Error | Error stopping the service: " + ex.ToString());
            }
        }

        private ServiceHost SetupWcfService()
        {
            IService serviceInstance = new Service.Service();
            ServiceHost host = new ServiceHost(serviceInstance);
            string baseaddr = String.Format("http://{0}:80/Service.svc", Environment.MachineName);

            WSDualHttpBinding binding = new WSDualHttpBinding(WSDualHttpSecurityMode.None);
            binding.SendTimeout = new TimeSpan(0, 0, 3);
            binding.OpenTimeout = new TimeSpan(0, 0, 20);
            binding.CloseTimeout = new TimeSpan(0, 0, 20);
            host.AddServiceEndpoint(typeof(IService), binding, baseaddr);

            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            smb.HttpGetUrl = new Uri(baseaddr);
            host.Description.Behaviors.Add(smb);

            return host;
        }
    }
}
